<template>
  <div class="wrapper-list">
    <!-- 条件区 -->
    <div class="wrapper-condition">
      <el-form :inline="true" label-position="left" label-width="80px" size="small">
        <el-form-item>
          <el-button type="success" icon="Plus" @click="onAdd">添加新设置</el-button>
        </el-form-item>
        <el-form-item>
          <el-radio-group v-model="tag" @change="onTagChanged">
            <el-radio-button v-for="item in tagOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>

    <div class="wrapper-table">
      <el-table
        v-loading="flagLoading"
        :data="tblDataList"
        :header-cell-style="{ 'text-align': 'center' }"
        row-key="id"
        fit
        size="small"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column width="300" label="名称">
          <template #default="scope">
            <el-input v-if="scope.row.isEdit" v-model="scope.row.label" size="small" />
            <span v-else>{{ scope.row.label }}</span>
          </template>
        </el-table-column>

        <el-table-column label="值">
          <template #default="scope">
            <el-input v-if="scope.row.isEdit" v-model="scope.row.value" size="small" />
            <span v-else>{{ scope.row.value }}</span>
          </template>
        </el-table-column>

        <el-table-column width="500" label="简介">
          <template #default="scope">
            <el-input v-if="scope.row.isEdit" v-model="scope.row.remark" size="small" />
            <span v-else>{{ scope.row.remark }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" width="120" label="操作">
          <template #default="scope">
            <div class="wrapper-op">
              <a v-if="!scope.row.isEdit" title="修改" class="ibtn ibtn-edit" @click="onEdit(scope.row)">
                <el-icon><Edit /></el-icon>
              </a>
              <a v-if="scope.row.isEdit" title="保存" class="ibtn ibtn-save" @click="onSave(scope.row)">
                <el-icon><Check /></el-icon>
              </a>
              <a
                v-if="scope.row.isEdit"
                title="取消"
                class="ibtn ibtn-cancel"
                @click="onCancel(scope.row, scope.$index)"
              >
                <el-icon><Close /></el-icon>
              </a>
              <a v-if="!scope.row.isEdit" title="删除" class="ibtn ibtn-del" @click="onDelete(scope.row.id)">
                <el-icon><Delete /></el-icon>
              </a>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { toastError, toastSuccess } from '@/utils/toast'
import { ElMessageBox } from 'element-plus'

import store from '@/store'
import { defineComponent, ref, onMounted } from 'vue'
export default defineComponent({
  name: 'GlobalOptionListAllView',
  components: {},
  setup() {
    const flagLoading = ref(false)
    const tblDataList = ref([])
    const tag = ref('Basic')
    const tagOptions = ref([
      { value: 'Basic', label: '基本设置' },
      { value: 'Upload', label: '上传设置' },
    ])
    // 当前页面是否处于添加新记录状态
    const flagAdding = ref(false)
    // 当前页面是否处于编辑状态
    const flagEditing = ref(false)

    // 点击tab事件
    const onTagChanged = (e) => {
      tag.value = e
      listAll()
    }
    // 获取所有设置
    const listAll = () => {
      flagLoading.value = true
      store
        .dispatch('sys_config/listAll', tag.value)
        .then((response) => {
          flagLoading.value = false
          response.map((item) => {
            item.isEdit = false
            item.isAdd = false
          })
          tblDataList.value = response
        })
        .catch(() => {
          flagLoading.value = false
        })
    }
    // 添加
    const onAdd = () => {
      // 设置当前全局编辑状态为true，使每行的编辑按钮失效
      flagEditing.value = true
      // 如果当前未处于添加新记录状态，则添加新记录
      if (!flagAdding.value) {
        // 设置 flagAdding 为 true ，使点击添加新记录按钮时，新增效果无效
        flagAdding.value = true
        const newConfig = {
          id: 0,
          tag: tag.value,
          label: '',
          value: '',
          remark: '',
          flagSystem: true,
          // isEdit 应为 true ，使新行操作区的保存取消按钮正常显示，并隐藏编辑删除按钮
          isEdit: true,
          // isAdd 应为 true，点击保存时，就跳到新增记录方法
          isAdd: true,
        }
        tblDataList.value.push(newConfig)
      }
    }
    // 点击编辑按钮
    const onEdit = (row) => {
      // 根据当前的 flagEditing 的值判断当前是否为编辑状态，保证只能编辑一行
      if (!flagEditing.value) {
        row.isEdit = true
      }
      // 设置 flagAdding 为 true ，使点击添加新记录按钮无效
      flagAdding.value = true
      // 设置全局的编辑状态为true，使其他行的编辑按钮失效
      flagEditing.value = true
    }
    // 编辑完成，点击保存
    const onSave = (row) => {
      // 数据校验
      if (row.label === '') {
        toastError('设置的名称不能为空！')
        return false
      }
      if (row.value === '') {
        toastError('设置的值不能为空！')
        return false
      }
      if (row.isAdd) {
        saveToDb(row)
      } else {
        updateData(row)
      }
    }
    // 取消编辑
    const onCancel = (row, index) => {
      // 如果当前是添加新记录状态
      if (flagAdding.value && row.isAdd) {
        // 如果当前是新增状态，将 table 最后一条记录删除
        tblDataList.value.splice(index, 1)
      } else if (flagEditing.value && row.isEdit) {
        // 如果当前是编辑状态，取消编辑当前的数据
        row.isEdit = false
      }
      // 点击了取消，此时页面没有进入编辑状态，也没有进入新增记录状态
      // 此时点击新增按钮应该是有效的
      flagAdding.value = false
      // 此时可编辑其他数据
      flagEditing.value = false
    }
    const onDelete = (id) => {
      ElMessageBox.confirm('确定要删除该条设置吗？', '警告', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        store
          .dispatch('sys_config/delById', id)
          .then(() => {
            toastSuccess('删除成功！')
            listAll()
          })
          .catch((error) => {
            console.log('删除出现错误：', error)
          })
      })
    }
    const saveToDb = (config) => {
      store
        .dispatch('sys_config/add', config)
        .then(() => {
          toastSuccess('添加成功！')
          flagEditing.value = false
          flagAdding.value = false
          listAll()
        })
        .catch(() => {})
    }
    const updateData = (config) => {
      store
        .dispatch('sys_config/modifyAll', config)
        .then(() => {
          toastSuccess('修改成功！')
          flagEditing.value = false
          flagAdding.value = false
          listAll()
        })
        .catch(() => {})
    }

    onMounted(() => {
      listAll()
    })

    return {
      flagLoading,
      tblDataList,
      tag,
      tagOptions,
      flagEditing,
      flagAdding,
      onAdd,
      onTagChanged,
      listAll,
      onEdit,
      onSave,
      onCancel,
      onDelete,
      saveToDb,
      updateData,
    }
  },
})
</script>

<style lang="scss" scoped>
.wrapper-tag {
  margin-bottom: 10px;
}
</style>
